import { Injectable, NestMiddleware } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { NextFunction } from 'express'
import { HEAD_TOKEN } from '../contants/config.contants'
import { JwtExistException, JwtInvalidException } from '../exception/JwtException'
import { ConfigurationKeys } from '../resources'

@Injectable()
export class JwtHandle implements NestMiddleware {
  constructor(private readonly _jwt: JwtService, private readonly config: ConfigService<ConfigurationKeys>) { }

  async use(request: Request, response: Response, next: NextFunction) {
    const token = request.headers[HEAD_TOKEN] as string

    if (token) {
      await this._jwt.verifyAsync(token, {
        secret: this.config.get('jwt.secretkey'),
        ignoreExpiration: false,
      }).then(() => {
        next()
      }).catch(() => {
        throw new JwtInvalidException()
      })
    } else {
      throw new JwtExistException()
    }
  }
}
